//
//  QFDatePickerView.m
//  dateDemo
//
//  Created by 情风 on 2017/1/12.
//  Copyright © 2017年 情风. All rights reserved.
//

#import "QFDatePickerView.h"
#import "AppDelegate.h"

@interface QFDatePickerView () <UIPickerViewDataSource,UIPickerViewDelegate>{
    void(^backBlock)(NSString *);
    NSMutableArray *yearArray;
    NSMutableArray *monthArray;
    NSInteger currentYear;
    NSInteger currentMonth;
    
    NSInteger selectedYear;
    NSInteger selectedMonth;
    
    UIView *_superView;
}

@property (nonatomic) NSInteger startYear;

@property (nonatomic) NSInteger startMonth;

@property (nonatomic, strong) UIPickerView *pickerView;

@property (nonatomic, strong) UIView *contentView;

@end

@implementation QFDatePickerView

#pragma mark - initDatePickerView
/**
 初始化方法，只带年月的日期选择
 
 @param block 返回选中的日期
 @return QFDatePickerView对象
 */
- (instancetype)initDatePackerWithStartYear:(NSInteger)year startMonth:(NSInteger)month Response:(void (^)(NSString *))block {
    if (self = [super init]) {
        self.frame = [UIScreen mainScreen].bounds;
    }
    self.startYear = year;
    self.startMonth = month;
    [self setViewInterface];
    if (block) {
        backBlock = block;
    }
    return self;
}

/**
 初始化方法，只带年月的日期选择
 
 @param superView picker的载体View
 @param block 返回选中的日期
 @return QFDatePickerView对象
 */
- (instancetype)initDatePackerWithStartYear:(NSInteger)year startMonth:(NSInteger)month superView:(UIView *)superView response:(void(^)(NSString*))block {
    if (self = [super init]) {
        self.frame = [UIScreen mainScreen].bounds;
    }
    self.startYear = year;
    self.startMonth = month;
    [self setViewInterface];
    if (block) {
        backBlock = block;
    }
    _superView = superView;
    return self;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    [self dismiss];
}

#pragma mark - Configuration
- (void)setViewInterface {
    
    [self getCurrentDate];
    
    [self setDateArray];
    
    self.contentView = [[UIView alloc] initWithFrame:CGRectMake(0, self.frame.size.height, self.frame.size.width, 300)];
    [self addSubview:self.contentView];
    //设置背景颜色为黑色，并有0.4的透明度
    self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
    //添加白色view
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 40)];
    whiteView.backgroundColor = COLORHEX(@"8e929f");
    [whiteView acs_radiusWithRadius:7 corner:UIRectCornerTopLeft | UIRectCornerTopRight];
    [self.contentView addSubview:whiteView];
    //添加确定和取消按钮
    for (int i = 0; i < 2; i ++) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake((self.frame.size.width - 60) * i, 0, 60, 40)];
        [button setTitle:i == 0 ? @"取消" : @"确定" forState:UIControlStateNormal];
        if (i == 0) {
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        } else {
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        [whiteView addSubview:button];
        [button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = 10 + i;
    }
    
    UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 40, CGRectGetWidth(self.bounds), 260)];
    pickerView.delegate = self;
    pickerView.dataSource = self;
    pickerView.backgroundColor = [UIColor colorWithRed:240.0/255 green:243.0/255 blue:250.0/255 alpha:1];
    self.pickerView = pickerView;
    //设置pickerView默认选中当前时间
    [pickerView selectRow:selectedYear - self.startYear inComponent:0 animated:YES];
    [pickerView selectRow:selectedMonth - 1 inComponent:1 animated:YES];
    
    [self.contentView addSubview:pickerView];
}

- (void)getCurrentDate {
    //获取当前时间 （时间格式支持自定义）
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM"];//自定义时间格式
    NSString *currentDateStr = [formatter stringFromDate:[NSDate date]];
    //拆分年月成数组
    NSArray *dateArray = [currentDateStr componentsSeparatedByString:@"-"];
    if (dateArray.count == 2) {//年 月
        currentYear = [[dateArray firstObject]integerValue];
        currentMonth =  [dateArray[1] integerValue];
    }
    selectedYear = currentYear;
    selectedMonth = currentMonth;
}

- (void)setDateArray {
    //初始化年数据源数组
    yearArray = [[NSMutableArray alloc]init];
    for (NSInteger i = self.startYear; i <= currentYear ; i++) {
        NSString *yearStr = [NSString stringWithFormat:@"%ld",(long)i];
        [yearArray addObject:yearStr];
    }
    
    monthArray = [NSMutableArray new];
    for (NSInteger i = 1; i <= 12; i++) {
        NSString *monthStr = [NSString stringWithFormat:@"%ld",(long)i];
        [monthArray addObject:monthStr];
    }
}

#pragma mark - Actions
- (void)buttonTapped:(UIButton *)sender {
    if (sender.tag == 10) {
        [self dismiss];
    } else {
        NSString *str = [NSString stringWithFormat:@"%@年%@月", yearArray[[self.pickerView selectedRowInComponent:0]], monthArray[[self.pickerView selectedRowInComponent:1]]];
        backBlock(str);
        [self.subject sendNext:@{@"year": yearArray[[self.pickerView selectedRowInComponent:0]],
                                 @"month": monthArray[[self.pickerView selectedRowInComponent:1]]}];
        [self dismiss];
    }
}

#pragma mark - pickerView出现
- (void)show {
    if (_superView) {
        [_superView addSubview:self];
    } else {
        [[UIApplication sharedApplication].keyWindow addSubview:self];
    }
    [UIView animateWithDuration:0.4 animations:^{
        self.contentView.center = CGPointMake(self.frame.size.width/2, self.contentView.center.y - self.contentView.frame.size.height);
    }];
}
#pragma mark - pickerView消失
- (void)dismiss{
    
    [UIView animateWithDuration:0.4 animations:^{
        self.contentView.center = CGPointMake(self.frame.size.width/2, self.contentView.center.y + self.contentView.frame.size.height);
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

#pragma mark - UIPickerViewDataSource UIPickerViewDelegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return yearArray.count;
    } else {
        return monthArray.count;
    }
}




- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (component == 0) {
        NSString *yearStr = yearArray[row];
        return yearStr;
    } else {
        NSString *monthStr = monthArray[row];
        return monthStr;
    }
    return @"";
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 40;
}

// 选中行
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    [pickerView reloadAllComponents];
    if (component == 0) {
        NSInteger year = [yearArray[row] integerValue];
        selectedYear = year;
        if (year == self.startYear) {
            [pickerView selectRow:self.startMonth - 1 inComponent:1 animated:YES];
        } else {
            [pickerView selectRow:0 inComponent:1 animated:YES];
        }
    } else {
        selectedMonth = [monthArray[row] integerValue];
        if (selectedYear == self.startYear) {
            if (row + 1 < self.startMonth) {
                [pickerView selectRow:self.startMonth - 1 inComponent:1 animated:YES];
            }
        } else if (selectedYear == currentYear) {
            if (row + 1 >= currentMonth) {
                [pickerView selectRow:currentMonth - 1 inComponent:1 animated:YES];
            }
        }
    }
    NSLog(@"%ld年%ld月", selectedYear, selectedMonth);
}

- (RACSubject *)subject {
    if (!_subject) {
        _subject = [RACSubject subject];
    }
    return _subject;
}

@end
